// packageA/pages/partEnter/partEnter.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null,
    //用户权限
    authority:null,
    //筛选框
    showScreen:false,
    //筛选条件
    condition:{
      startTime:'请选择日期',
      endTime:'请选择日期',
      depot:{
        name:'请选择'
      }
    },
    //状态
    valueState: -1,
    //状态筛选
    optionState: [{
      value: -1,
      text: '全部状态'
    },{
      value: 1,
      text: '已完成'
    },{
      value: 2,
      text: '待入库'
    },{
      value: 3,
      text: '部分入库'
    }],
    //入库类型筛选
    typeList: [],
    //仓库
    depotList: [],
    //开始时间选择框
    showStartTime:false,
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2:null,
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } 
      return value
    },
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取列表数据
    this.getList();
    
    //获取入库类型字典
    this.getType();  
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      type:2,
      selectFields: ['id', 'inStorageType', 'factory', 'logistics', 'type', 'purchaseOrder', 'buyer', 'orderNo','depot', 'state', 'inStorageParts', 'inputDateTime', 'operator', 'remark', 'purchaseOrder','parts', 'server', 'detail', 'orderPersonnel', 'clerk'],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    } 

    //单号模糊查询
    if(this.data.searchValue){
      dataObj.orderNo='%' +this.data.searchValue+ '%';
    }

    let condition=this.data.condition;  

    //状态
    if(this.data.valueState!='-1'){      
      dataObj.state=this.data.valueState;
    }

    //入库类型
    if(condition.type && condition.type!='-1'){      
      dataObj['inStorageType.id']=condition.type;
    }

    //仓库
    if(condition.depot && condition.depot.id){      
      dataObj['depot.id']=condition.depot.id;
    }

    //入库日期
    if(condition.startTime && condition.startTime!='请选择日期' && condition.endTime && condition.endTime!='请选择日期'){      
      dataObj.complex=[{
        and: {
          operationDate: {
            ">=": condition.startTime + " 00:00:00",
            "<": condition.endTime + " 23:59:59"
          }
        }
      }]
    }  

    let param = {
      isAuth: true,
      className: 'inStorageOrder',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      console.log(res);
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //入库人
          if(item.operator && item.operator.name!="System") {
            item.custom_operatorName=item.operator.name;
          }else if(item.buyer){
            item.custom_operatorName=item.clerk.name; 
          }

          //入库时间
          if(item.inputDateTime){
            item.inputDateTime=util.timeFormat(item.inputDateTime);
          }

          //状态
          switch(item.state){
            case 1:
              item.stateWord='已完成';
              item.stateClass='c-1';
              break;
            case 2:
              item.stateWord='待入库';
              item.stateClass='c-7';
              break;
            case 3:
              item.stateWord='部分入库';
              item.stateClass='c-8';
              break;
          }
        });

        console.log('配件入库列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },
  
  //显示筛选
  onShowScreen(){
    this.setData({
			showScreen: true
    })
  },

  //隐藏筛选
  onCloseScreen(){
    this.setData({
      showScreen: false
    })
  },

  //改变状态
  onChangeState({detail}){
    this.setData({ 
      valueState: detail
    }) 
    this.refreshListAndPage();
  },

  //获取入库类型字典
  getType(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'inStorageType',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;

        let arr=[{
          id:-1,
          name:'全部'
        }];

        result.forEach(item => {
          arr.push({
            id:item.id,
            name:item.name
          });
        });

        this.setData({
          typeList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //点击入库类型
  onGetType(e){
    let detail=e.currentTarget.dataset.detail;

    let list=this.data.typeList;
    list.forEach(item => {
      item.current=false;
		  if (item.id==detail.id){
        item.current=true;
		  }
    });

    let type='condition.type';
    this.setData({
      [type]:detail.id,
      typeList:list
    })
  },

  //显示开始时间
  onShowStartTime(){
    this.setData({
			showStartTime: true
    })
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    let startTime='condition.startTime';
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      [startTime]:util.timeFormatDay(e.detail),
    })
    this.onCloseStartTime();
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
			showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    let endTime='condition.endTime';
    this.setData({
      currentEnd: e.detail,
      maxDate1:e.detail,
      [endTime]:util.timeFormatDay(e.detail),
    })
    this.onCloseEndTime();
  },

  //清除日期
  onClearDate(){
    let startTime='condition.startTime';
    let endTime='condition.endTime';
    this.setData({      
      [startTime]:'请选择日期',
      [endTime]:'请选择日期'
    })
  },

  //确认筛选
  onConfirm(e){
    let condition=this.data.condition;
    let start=condition.startTime;
    let end=condition.endTime;

    //入库日期不能只填一个
    if(start!='请选择日期' && end=='请选择日期'){
      Toast.fail('请选择结束日期');
      return;
    }else if(start=='请选择日期' && end!='请选择日期'){
      Toast.fail('请选择开始日期');
      return;
    }else{
      this.onCloseScreen();
      this.refreshListAndPage();
    } 
  },

  //重置
  onReset(){
    let typeList=this.data.typeList,
        depotList=this.data.depotList;
   
    this.listNotSelected(typeList,'typeList');
    this.listNotSelected(depotList,'depotList');

    this.setData({
      condition:{
        startTime:'请选择日期',
        endTime:'请选择日期'
      }
    })

    this.refreshListAndPage();
  },

  //批量处理列表
  listNotSelected(list,str){
    list.forEach(item => {
      item.current=false;
    });

    this.setData({
      [str]:list
    })
  },

  //跳转详情
  goToLook(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      id: detail.id,
      isRead: true
    }   

    wx.navigateTo({
      url: "/packageA/pages/partEnterEdit/partEnterEdit?paramObj="+JSON.stringify(obj)
    })
  },  

  //入库
  goToEnter(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      id: detail.id,
      isRead: false
    }   

    wx.navigateTo({
      url: "/packageA/pages/partEnterEdit/partEnterEdit?paramObj="+JSON.stringify(obj)
    })  
  },

  //作废
  onVoid(e){    
    Dialog.confirm({
      title: '确定作废此入库单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不作废了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;
      let param={
        className:'inStorageOrder',
        data:{
          id: detail.id,
          validState: 0
        }
      }

      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已作废');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })
    
    let dataset=e.currentTarget.dataset;
    let field=dataset.field;   
    
    this.setData({
      selectField: field,
      showSelect: true
    }) 

    //仓库
    if(field=='depot'){
      this.setData({
        selectTitle: '仓库',
        showSelectSearch:true
      })
      this.getDepotList();
    }  
  }, 

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: ''
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null; 

    //仓库
    if(selectField=='depot'){
      obj='condition.depot';
    }    

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }   
    
    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null; 

    //仓库
    if(selectField=='depot'){
      obj='condition.depot';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }
    
    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;
    
    this.setData({
      valueSearch: e.detail
    })

    //仓库
    if(selectField=='depot'){
      this.getDepotList();
    }
  },

  //查询仓库
  getDepotList(){
    let param = {
      isAuth: true,
      className: 'partsDepots',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }
   
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }else{
        this.setData({
          selectList: []
        }) 
      }
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})